package com.nf1000.balancelibrary.newbalance;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

@SuppressLint("NewApi")
@SuppressWarnings("unused")
public class LefuBluetoothController {
	private Handler mHandler;
	private Context mContext;
	private String mDeviceAddress;
	private BlueSingleton singleton;
	private int mStatus;
	private BluetoothDevice mDevice;
	/*mServiceConnection是否已绑定*/
	private boolean isServiceReg = false;
	/*mGattUpdateReceiver是否已释放注册*/
	private static boolean receiverReleased = true;
	private BluetoothAdapter mBluetoothAdapter;
	private boolean mIsScanning;
	private static LefuBluetoothController mLefuBluetoothController;
	
	/**构造方法*/
	private LefuBluetoothController(Context context, Handler handler) {
		this.mContext = context;
		this.mHandler = handler;
	}

	/**获取实例*/
	public static LefuBluetoothController getInstance(Context context, Handler handler) {
		if (mLefuBluetoothController == null) {
			mLefuBluetoothController = new LefuBluetoothController(context, handler);
		}
		return mLefuBluetoothController;
	}

	/**初始化蓝牙*/
	public void initBle() {
		final BluetoothManager bluetoothManager = (BluetoothManager) mContext.getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE);
		mBluetoothAdapter = bluetoothManager.getAdapter();
		singleton = BlueSingleton.getInstance(mHandler);
	}

	/**扫描关闭蓝牙设备*/
	public void scanDevice(boolean enable) {
		if (enable) {
			if (!singleton.getmScanning())
				singleton.scanLeDevice(true, mContext, mServiceConnection);
		} else {
			if (singleton.getmScanning())
				singleton.scanLeDevice(false, mContext, mServiceConnection);
		}
	}

	/**连接蓝牙设备*/
	public void connectBluetoothDevice(BluetoothDevice device) {
		if (receiverReleased) {
			IntentFilter intentFilter = new IntentFilter();
			intentFilter.addAction(IntentFilterConstant.ACTION_GATT_CONNECTED);
			intentFilter.addAction(IntentFilterConstant.ACTION_GATT_DISCONNECTED);
			intentFilter.addAction(IntentFilterConstant.ACTION_GATT_SERVICES_DISCOVERED);
			intentFilter.addAction(IntentFilterConstant.ACTION_DATA_AVAILABLE);
			mContext.registerReceiver(mGattUpdateReceiver, intentFilter);
			receiverReleased = false;
		}

		mDeviceAddress = device.getAddress();
		Intent gattServiceIntent = new Intent(mContext.getApplicationContext(), BluetoothLeService.class);
		mContext.getApplicationContext().bindService(gattServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
	}

	/**暂停调用*/
	public void onPause() {
		if (!receiverReleased) {
			receiverReleased = true;
			mContext.unregisterReceiver(mGattUpdateReceiver);
		}
	}

	/**Gatt广播接收器*/
	private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (IntentFilterConstant.ACTION_GATT_CONNECTED.equals(action)) {
				singleton.setmConnected(true);
			} else if (IntentFilterConstant.ACTION_GATT_DISCONNECTED.equals(action)) {
				if (singleton.getmConnected()) {
					singleton.setmConnected(false);
				}
				mStatus = BluetoothProfile.STATE_DISCONNECTED;
				mDevice = null;

				Message msg = mHandler.obtainMessage(ActionConstant.ACTION_GATT_DISCONNECTED);
				msg.obj = mDevice;
				mHandler.sendMessage(msg);

				if (isServiceReg){
					mContext.getApplicationContext().unbindService(mServiceConnection);
				}
			} else if (IntentFilterConstant.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
				mStatus = BluetoothProfile.STATE_CONNECTED;
				mDevice = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);

				Message msg = mHandler.obtainMessage(ActionConstant.ACTION_GATT_SERVICES_DISCOVERED);
				msg.obj = mDevice;
				mHandler.sendMessage(msg);
			} else if (IntentFilterConstant.ACTION_DATA_AVAILABLE.equals(action)) {
				final byte[] value = intent.getByteArrayExtra(IntentFilterConstant.EXTRA_DATA);
				mDevice = null;
				if (singleton.getmConnected()){
					singleton.setmConnected(false);
				}

				Message msg = mHandler.obtainMessage(ActionConstant.ACTION_DATA_AVAILABLE);
				msg.obj = value;
				mHandler.sendMessage(msg);

				if (isServiceReg) {
					mContext.getApplicationContext().unbindService(mServiceConnection);
					isServiceReg = false;
				}
			}
		}
	};

	/**连接服务*/
	public final ServiceConnection mServiceConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName componentName, IBinder service) {
			isServiceReg = true;
		}

		@Override
		public void onServiceDisconnected(ComponentName componentName) {

			isServiceReg = false;
		}
	};

}
